/**
 * Created by Administrator on 2018/1/1.
 */
layui.config({
    base: '../build/js/'
}).use(['ztree', 'layer','table','form','treeselect'], function() {
    var $ = layui.jquery,
        layer = layui.layer
        ,table = layui.table
        ,form = layui.form
        ,treeselect = layui.treeselect
        ,zTreeObj=null
        ,departmentTreeObj=null
        ,addRoleLayer=null
        ,assignPermissionsLayer=null
        ,selectRole=null
        ,selectDepartNode=null
        ,isAdd=true
        ,departments=[];
    var queryParam={keyWord:'',deptId:0};

    var setting = {
        view: {
            selectedMulti: false
        },
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        edit: {
            enable: false
        }
    };

    //初始化树
    function initZTree() {
        $.post("/sysMenu/menuTree", {systemId:"upms"}, function(res) {
            if(res){
                zTreeObj =$.fn.zTree.init($("#ztree"), setting, res);
                zTreeObj.expandAll(true);
            }
        }, 'json');
    }
    
    function initDepartmentTree() {
        $.post("/department/select", {pId:0,keyWord:""}, function(res) {
            if(res){
                if(res.code==0){
                    departments=res.data;
                    departmentTreeObj =$.fn.zTree.init($("#departmentTree"), setting, departments);
                    departmentTreeObj.setting.check.enable=false;
                    departmentTreeObj.setting.callback.onClick=selectDepartment;
                    departmentTreeObj.expandAll(true);
                    //
                    // treeselect.render({
                    //     elem:'#deptSelectTree',
                    //     check:false,
                    //     data:departments
                    // })
                }else {
                    layer.msg(res.msg, {
                        icon: 2,
                        time:3000
                    });
                }
            }
        }, 'json');
    }
    
    function selectDepartment(event, treeId, treeNode) {
        queryParam.deptId=treeNode.id;
        selectDepartNode=treeNode;
        table.reload('rolesTable', {
            where: queryParam
        });
    }

    $(document).ready(function() {
        initZTree();
        initDepartmentTree();
    });

    //加载子级菜单列表
    table.render({
        elem: '#roles'
        ,url:'/role/selectRoles'
        ,where:queryParam
        ,method:'post'
        ,limit:15
        ,cellMinWidth: 80
        ,cols: [[
            {type: 'checkbox'}
            ,{field:'name', title:'名称'}
            ,{field:'title', title:'标题',minWidth:120}
            ,{field:'description', title: '描述',minWidth:120}
            ,{field:'orders', title: '排序',minWidth:40}
            ,{fixed: 'right', width:150, align:'center', toolbar: '#barMenus'}
        ]]
        ,page:true
        ,id: 'rolesTable'
    });

    //监听工具条
    table.on('tool(roles)', function(obj){
        var data = obj.data;
        if(obj.event === 'del'){
            layer.confirm('真的删除角色信息么', function(index){
                var roleIds=[];
                roleIds.push(data.id);
                excDeleteRoles(roleIds);
            });
        }
        else if(obj.event ==='assignPermission'){
            selectRole=data;
            assignPermissionsLayer=layer.open({
                title:"权限分配",
                type:1,
                area: ['25%', '100%'],
                offset: 'r',
                anim: 2,
                scrollbar:true,
                resize:true,
                maxmin:true,
                content:$("#permissionTree")
            });

            //查询角色权限信息
            var queryPermissionParam={};
            queryPermissionParam.roleId=data.id;
            queryPermissionParam.systemId="upms";
            selectRolePermissions(queryPermissionParam);
        }
        else if(obj.event==='updateRole'){
            isAdd=false;
            $("input[name='id']").val(data.id);
            $("input[name='name']").val(data.name);
            $("input[name='title']").val(data.title);
            $("input[name='description']").val(data.description);
            $("input[name='deptId']").attr("value",data.deptId);
            $("input[name='orders']").val(data.orders);
            treeselect.render({
                elem:'#deptSelectTree',
                check:false,
                data:departments
            });
            addRoleLayer=layer.open({
                type:1,
                area:'35%',
                offset:'20%',
                maxmin:true,
                skin:'layui-layer-molv',
                content:$("#addRoleForm")
            });
        }
    });


    var active = {
        addRole: function(){
            isAdd=true;
            // $("input[name='id']").val("");
            $("input[name='name']").val("");
            $("input[name='title']").val("");
            $("input[name='description']").val("");
            $("#deptSelectTree").attr("value","");
            $("input[name='orders']").val("");
            treeselect.render({
                elem:'#deptSelectTree',
                check:false,
                data:departments
            });

            addRoleLayer=layer.open({
                type:1,
                area:'35%',
                offset:'20%',
                maxmin:true,
                skin:'layui-layer-molv',
                content:$("#addRoleForm")
            });
        },
        deleteRoles:function () {
            var checkStatus = table.checkStatus('rolesTable')
                ,data = checkStatus.data
                ,roleIds=[];
            for (var i=0;i<data.length;i++){
                roleIds.push(data[i].id);
            }

            excDeleteRoles(roleIds);
        },
        saveRolePermission:function () {
            var nodes = zTreeObj.getCheckedNodes(true);
            var permissionIds=[];
            var systemId="";
            if(nodes){
                for (var i=0;i<nodes.length;i++){
                    var node=nodes[i];
                    permissionIds.push(node.id);
                    systemId=node.systemId;
                }

                var params={};
                params.roleId=selectRole.id;
                params.systemId=systemId;
                params.permissions=permissionIds;

                $.ajax({
                    type: "POST",
                    url: "../permission/assign",
                    dataType:'json',
                    contentType:'application/json;charset=utf-8',
                    data: JSON.stringify(params),
                    success: function(res){
                        if(res){
                            if(res.code==0){
                                layer.msg(res.msg, {
                                    icon: 1,
                                    time: 3000 //3s后自动关闭
                                });
                            }else{
                                layer.msg(res.msg, {
                                    icon: 2,
                                    time:3000
                                });
                            }
                        }
                    }
                });
            }
        }
    };

    function excDeleteRoles(roleIds) {
        $.post("../role/deleteRoles",{roleIds:roleIds}, function(res) {
            if(res){
                if(res.code==0){
                    layer.msg(res.msg, {
                        icon: 1,
                        time: 3000 //3s后自动关闭
                    });
                    table.reload('rolesTable', {
                        where: queryParam
                    });
                }else{
                    layer.msg(res.msg, {
                        icon: 2,
                        time:3000
                    });
                }
            }
        }, 'json');
    }
    
    function selectRolePermissions(params) {
        $.ajax({
            type: "POST",
            url: "../permission/selectRolePermission",
            dataType:'json',
            data:params,
            success: function(res){
                if(res){
                    if(res.code==0){
                        var permissions=res.data;
                        zTreeObj.checkAllNodes(false);
                        if(permissions){
                            for (var i=0;i<permissions.length;i++){
                                var permission=permissions[i];
                                var id=permission.permissionId;
                                var node=zTreeObj.getNodeByParam("id",id, null);
                                if(!(node.children && node.children.length>0)){
                                    zTreeObj.checkNode(node, true, true);
                                }
                            }
                        }
                    }else{
                        layer.msg(res.msg, {
                            icon: 2,
                            time:3000
                        });
                    }
                }
            }
        });
    }

    //添加
    form.on('submit(addRoleSubmit)', function(data) {
        var loadIndex = layer.load(2, {
            shade: [0.3, '#333']
        });

        var url="../role/addRole";
        if(!isAdd){
            url="../role/updateRole"
        }

        $.post(url,data.field, function(res) {
            loadIndex && layer.close(loadIndex);
            if(res.code==0){
                layer.msg(res.msg, {
                    icon: 1,
                    time:3000
                });
                layer.close(addRoleLayer);
                table.reload('rolesTable', {
                    where: queryParam
                });
            }else{
                layer.msg(res.msg, {
                    icon: 2,
                    time:3000
                });
            }
        }, 'json');
    });

    $('.roleToolBar .layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
});